package com.atguigu.yygh.msm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.RandomUtil;
import com.atguigu.yygh.vo.msm.MsmVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class MsmServiceImpl implements MsmService {
    //调用接口方法发送短信
    @Override
    public boolean send(String phone, Map<String, Object> param) {
        //0手机号校验
        if(StringUtils.isEmpty(phone)) return false;
        //1创建客户端对象
        DefaultProfile profile =
                DefaultProfile.getProfile("default",
                        "LTAI5tMGtKPbL2bCp6zSU4Bz",
                        "baAdNzxAjnIMKU3wroxZLlpAACpy02");
        IAcsClient client = new DefaultAcsClient(profile);
        //2创建请求对象，存入参数
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "我的谷粒在线教育网站");
        request.putQueryParameter("TemplateCode", "SMS_183195440");
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
        try {
            //3客户端对象调用方法发送请求，获得响应
            CommonResponse response = client.getCommonResponse(request);
            //4从响应中获得结果
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ClientException e) {
            e.printStackTrace();
            throw new YyghException(20001,"发送短信失败");
        }

    }

    @Override
    public boolean send(MsmVo msmVo) {
        //取出参数
        String phone = msmVo.getPhone();
        String templateCode = msmVo.getTemplateCode();
        Map<String, Object> param = msmVo.getParam();
        //测试短信
        String code = RandomUtil.getFourBitRandom();
        Map<String, Object> paramTest = new HashMap<>();
        paramTest.put("code",code);
        boolean isSend = this.send(phone, paramTest);
        return isSend;
    }
}
